<?php

namespace backend\controllers;

use Yii;
use backend\models\Image;
use backend\models\ImageSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\UploadForm;
use backend\models\PrfType;

use liangzoe\mobilesmser\TextSmser;
use yii\web\UploadedFile;
use PHPThumb\GD;
use yii\db\Query;
use yii\web\ForbiddenHttpException;
use backend\models\SysImage;
use backend\models\UploadFlashForm;
use backend\models\Show;

/**
 * ImageController implements the CRUD actions for Image model.
 */
class ImageController extends Controller
{
	
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('image-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all Image models.
     * @return mixed
     */
    public function actionIndex()
    {
        
      
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	/* return $this->render('index',[
    			'model' => $model,
    			]); */
    	/*
        $searchModel = new ImageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);*/
    	//lwx 2019/10/10 修改算法 
    	$img_id=0;
    	$get=Yii::$app->request->get();
    	if(key_exists("show_id", $get)){
    	    $img_id=$get["show_id"];
    	    
    	}
    	//新套装
    	$newtaozhuang_list2=PrfType::findNewtaozhuangList();
    	//秀家
    	$xiujia_list2=PrfType::findXiujiaList();
    	//老结构
    	$old_list2=PrfType::findOldList();
    	
    	//分类表
    	$cateList=PrfType::findCateList();
    	$return_data=['img_id'=>$img_id,'model'=>$model,'newtaozhuang_list2'=>$newtaozhuang_list2,'xiujia_list2'=>$xiujia_list2,"old_list2"=>$old_list2,"cateList"=>$cateList];
    	return $this->render('index',$return_data);
    }
	
    public function actionSelectTz()
    {
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	return $this->render('select_tz',[
    			'model' => $model,
    			]);
    }
    /**
     * Displays a single Image model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Image model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Image();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Image model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Image model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Image model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Image the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Image::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    /**
     * 分页显示图片
     * @param unknown $pageNum
     * @param unknown $img_type
     */
    public function actionShowImage($page,$search,$tag)
    {
    	
    	//$page = intval($_POST['pageNum']); //当前页
    	//$page = $page;
    	if($tag == 'type')
    	$total = Image::find()->where(['type'=>$search])->count(); //总记录数
    	if($tag == 'name')
    		$total = Image::findBySql("select * from sys_image where name like '%".$search."%'")->count();
    		//$total = Image::findBySql("select * from sys_image where name like ':search'",[':search'=>$search])->count();
    	/*	$total = (new Query())
    		->select('*')
    		->from('sys_image')
    		->where('name like "%:search%"', [':search' => $search])
    		->count();*/

    	//$total = Image::find()->where(['name'=>$search])->count();
    	
    	
    	$pageSize = 10; //每页显示数
    	$totalPage = ceil($total/$pageSize); //总页数
    	
    	$startPage = $page*$pageSize;//开始记录
    	//构造数组
    	
    	$arr['total'] = $total;
    	$arr['pageSize'] = $pageSize;
    	$arr['totalPage'] = $totalPage;
    	if($tag == 'type')
    	$result = Image::findBySql("select * from sys_image where type=".$search." order by id desc limit ". $startPage . "," . $pageSize )->all();
    	if($tag == 'name')
    		$result = Image::findBySql("select * from sys_image where name like '%".$search."%' order by id desc limit ". $startPage . "," . $pageSize )->all();
    	 
    	if($result !=null)
    	{
	    	foreach ($result as $value )
	    	{
	    		$arr['list'][] = array(
	    				'id' => $value['id'],
	    				'type' => $value['type'],
	    				'name' => $value['name'],
	    				'url' => $value['url'],
	    				'width' => $value['width'],
	    				'height' => $value['height'],
	    				
	    		);
	    	}
	    	echo json_encode($arr); //输出JSON数据
    	}
    	
    	else {
    		$arr['list'][] = array(
    				'id' => '',
    				'type' => '',
    				'name' => '',
    				'url' => '',
    				'width' => '',
    				'height' => '');
    		
    		echo json_encode($arr);
    	}
    	
    	
    }
    
    /**
     * 上传图片
     * @param unknown $id
     * @return Ambigous <string, string>
     */
    public function actionUploadImage($type_id)
    {
    	$this->layout = 'main_small';
    	$model = new UploadForm();
    	$model->scenario = 'need_file_name';
    	 

    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
    	    $model->image_upload = UploadedFile::getInstance($model, 'image_upload');
    	    if ($model->image_upload && $model->validate()) {
    			$arr = $this->save_image_to_files($model,$type_id);  			 
    			if($arr !== null){
    				//echo $arr['img_show'];
    				return $this->render('upload_img',[
    						'model' => $model,
    						'arr_img' => $arr,
    					]);
    			}else{
    				echo '上传失败';
    		
    			}
    		}
    	}
    	 
    	return $this->render('upload_img', [
    			'model' => $model,
    			 
    			]);
    }
    
    /**
     * flash上传图片  不用写名称
     */
    public function actionUploadFlashImage($type_id){
        
        $this->layout = 'main_small';
        $model = new UploadFlashForm();
        $model->scenario = 'need_file_name';
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            $model->image_upload = UploadedFile::getInstance($model, 'image_upload');
            $model->name=$model->image_upload.""; 
            
           
            if ($model->image_upload && $model->validate()) {
                $arr = $this->update_flash_image_to_files($model,$type_id);
                
                if($arr !== null){
                     $model->url=$arr["img_url"];
                    //echo $arr['img_show'];
                    return $this->render('upload_flash_img',[
                        'model' => $model,
                    ]);
                } 
            }else{
                print_R($model);exit();
            }
        } 
         
        return $this->render('upload_flash_img', [
            'model' => $model,
            
        ]);
        
    }
    /**
     * 秀家修改底图直接创建图片
     */
    public function actionUploadFlashImageShow($showid){
        
        $this->layout = 'main_small';
        $model = new UploadFlashForm();
        $model->scenario = 'need_file_name';
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            $model->image_upload = UploadedFile::getInstance($model, 'image_upload');
            $model->name=$model->image_upload."";
            if ($model->image_upload && $model->validate()) {
               // $arr = $this->save_image_to_files($model,$showid);
                $arr=$this->save_imge_from_show($model,$showid);
                $img_id=$arr["img_url_id"];
                $img=Image::findOne($img_id);
                $model->url=$img->url;
                $show=Show::findOne($showid);
                $show->img_small_id=$arr["img_small_id"];
                $show->img_thumb_id=$arr["img_thumb_id"];
                $show->img_url_id=$arr["img_url_id"];
                $result=$show->save();
                return $this->render('upload_flash_img', [
                    'model' => $model,
                ]);
               // return $this->redirect(['show/img-update','id'=>$showid]);
            }else{
                print_R($model);exit();
            }
        }
        
        return $this->render('upload_flash_img', [
            'model' => $model,
            
        ]);
    }
    /**
     * flash修改图片  不用写名称
     */
    public function actionFlashUpdateImage($id){
        
        $this->layout = 'main_small';
        $model = new UploadFlashForm();
        $model->scenario = 'need_file_name';
        $img_model=Image::findOne($id);
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            $type_id=$img_model->type;
            $model->url=$img_model->url;
            $model->id=$img_model->id;
            $model->name=$model->image_upload;
            $model->image_upload = UploadedFile::getInstance($model, 'image_upload');
 
           // $model->name=$model->image_upload."";
            if ($model->image_upload && $model->validate()) {
                $arr = $this->update_flash_image_to_files($model,$type_id);
                if($arr !== null){
                    $model->url=$arr["img_url"];
                    //echo $arr['img_show'];
                    return $this->render('upload_flash_img',[
                        'model' => $model,
                    ]);
                }
            }else{
                print_R($model);exit();
            }
        }else{
            
           
            $model->image_upload=$img_model->url;
            $model->url=$img_model->url;
            
        }
        return $this->render('upload_flash_img', [
            'model' => $model,
            
        ]);
        
    }
    /**
     * flash修改图片
     */
    public function update_flash_image_to_files($model,$file_menu){
        $id=$model->id;
        $uuid = md5(uniqid());
        $uuid_a =  substr($uuid, 0,3);
        $uuid_b =substr($uuid, 3,3);
        $uuid_c = substr($uuid, 6,3);
        $uuid_d =  substr($uuid, 9,3);
        $uuid_file_name =  substr($uuid, 12,20);
        $folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
        TextSmser::make_dir($folder);
        $file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置
        
      
        $model->image_upload->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension);
        $image_name = $model->image_upload." ";
        
       
        $image_addr = $file_save_addr.'.'.$model->image_upload->extension;
        $image_url = $file_menu;
        $image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[0];
        $image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[1];
        $img_url_id=$this->updateimage($id,$image_name, $image_w, $image_h,$image_addr);
        $img_url = $file_save_addr.'.'.$model->image_upload->extension;
        return array('img_url'=>$img_url);
        
    }
    /**
     * 共用--存入数据到文件夹，并获取缩略图，三种图片的id
     * @param unknown $model
     * @param number $width1
     * @param number $height1
     * @param number $width2
     * @param number $height2
     * @return multitype:string boolean Ambigous <boolean, number>
     */
    public function save_image_to_files($model,$file_menu)
    {
    	 
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3); 	 
    	$uuid_file_name =  substr($uuid, 12,20); 	 
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    	   	
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置   	 
    	$model->image_upload->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension);
    	$image_name = $model->name;
    	
    	$image_addr = $file_save_addr.'.'.$model->image_upload->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[1];
    
    	$img_url_id = $this->newimage($image_name,$image_addr, $file_menu, $image_w, $image_h);
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->image_upload->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->image_upload->extension; 
    	
    	//生成缩略图并记录到数据库（中图）,大于990的时候
    	if( $image_w / 2 >= 990)
    	{	    
    	    $thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension); //原图
	    	//$thumb->resize($width1,$height1);
	    	$thumb->resizePercent(50);
	    	$file_save_addr_thumb = $file_save_addr.'_1';//实际位置
	    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension);
	    
	    	$image_addr_thumb = $file_save_addr_thumb.'.'.$model->image_upload->extension;
	    	$image_url_thumb = $file_menu;//虚拟目录（图片类别）
	    	$image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension)[0];
	    	$image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension)[1];
	    
	    	$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension.'">';
	    	$img_thumb_url = $file_save_addr_thumb.'.'.$model->image_upload->extension;
    	}
    	else 
    	{
    		$img_thumb_url = '';
    	}

    	
    	//生成缩略图并记录到数据库（小图）
    	if( $image_w /4 >=  300)
    	{
	    	//$thumb->resize($width2,$height2);
	    	$small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);//原图
	    	$small->resizePercent(25);
	    	$file_save_addr_small = $file_save_addr.'_2';//实际位置
	    	$small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension);
	        
	    	$image_addr_small = $file_save_addr_small.'.'.$model->file->extension;
	    	$image_url_small = $file_menu;//虚拟目录（图片类别）
	    	$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[0];
	    	$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[1];
	    
	    	$img_small_id = $this->newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_small.'.'.$model->file->extension.'">';
	    	$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
	    	$img_small_url = $file_save_addr_small.'.'.$model->file->extension;
	    	
    	}
    	else
    	{
    		$img_small_url= '';
    	}
    	return array('img_url'=>$img_url,'img_thumb_url'=>$img_thumb_url,'img_small_url'=>$img_small_url,'img_show'=>$img_show);
    	//return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    }
         public function save_image_to_files_old($model,$file_menu)
    {
    	 
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3);
    	 
    	$uuid_file_name =  substr($uuid, 12,20);
    	 
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    	 
    	
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置
    	 
    	$model->file->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    	$image_name = $model->name;
    	
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_url_id = $this->newimage($image_name,$image_addr, $image_url, $image_w, $image_h);
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->file->extension; 
    	//生成缩略图并记录到数据库（中图）
    	$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    
    	//$thumb->resize($width1,$height1);
    	$thumb->resizePercent(50);
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name.'_1';//实际位置
    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;//虚拟目录（图片类别）
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr, $image_url, $image_w, $image_h);
    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_thumb_url = $file_save_addr.'.'.$model->file->extension;
    	//生成缩略图并记录到数据库（小图）
    	//$thumb->resize($width2,$height2);
    	$thumb->resizePercent(50);
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name.'_2';//实际位置
    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    
    
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;//虚拟目录（图片类别）
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_small_id = $this->newimage($image_name.'_small',$image_addr, $image_url, $image_w, $image_h);
    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
    	$img_small_url = $file_save_addr.'.'.$model->file->extension;
    	//return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    	
    	return array('img_url'=>$img_url,'img_thumb_url'=>$img_thumb_url,'img_small_url'=>$img_small_url,'img_show'=>$img_show);
    	
    }
     
   
    
   /**
    * 秀家修改图片
    */
    public function save_imge_from_show($model,$file_menu){
        
        //设置默认三个图片id为0
        $img_small_id=0; 
        $img_url_id=0;
        $img_thumb_id=0;
        
        $uuid = md5(uniqid());
        $uuid_a =  substr($uuid, 0,3);
        $uuid_b =substr($uuid, 3,3);
        $uuid_c = substr($uuid, 6,3);
        $uuid_d =  substr($uuid, 9,3);
        $uuid_file_name =  substr($uuid, 12,20);
        $folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
        TextSmser::make_dir($folder);
        
        $file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置
        $model->image_upload->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension);
        $image_name = $model->name;
        
        $image_addr = $file_save_addr.'.'.$model->image_upload->extension;
        $image_url = $file_menu;
        $image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[0];
        $image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[1];
        
        $img_url_id = $this->newimage($image_name,$image_addr, $file_menu, $image_w, $image_h);
        $img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->image_upload->extension.'">';
        $img_url = $file_save_addr.'.'.$model->image_upload->extension;
        
        //生成缩略图并记录到数据库（中图）,大于990的时候
        if( $image_w / 2 >= 990)
        {
            $thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension); //原图
            //$thumb->resize($width1,$height1);
            $thumb->resizePercent(50);
            $file_save_addr_thumb = $file_save_addr.'_1';//实际位置
            $thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension);
            
            $image_addr_thumb = $file_save_addr_thumb.'.'.$model->image_upload->extension;
            $image_url_thumb = $file_menu;//虚拟目录（图片类别）
            $image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension)[0];
            $image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension)[1];
            
            $img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
            $img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension.'">';
            $img_thumb_url = $file_save_addr_thumb.'.'.$model->image_upload->extension;
        }
        else
        {
            $img_thumb_url = '';
        }
        
        
        //生成缩略图并记录到数据库（小图）
        if( $image_w /4 >=  300)
        {
            //$thumb->resize($width2,$height2);
            $small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);//原图
            $small->resizePercent(25);
            $file_save_addr_small = $file_save_addr.'_2';//实际位置
            $small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension);
            
            $image_addr_small = $file_save_addr_small.'.'.$model->file->extension;
            $image_url_small = $file_menu;//虚拟目录（图片类别）
            $image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[0];
            $image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[1];
            $img_small_id = $this->newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
            $img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_small.'.'.$model->file->extension.'">';
            $img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
            $img_small_url = $file_save_addr_small.'.'.$model->file->extension;
            
        }
        else
        {
            $img_small_url= '';
        }
        if($img_small_id==0){
            $img_small_id=$img_url_id;
        }
        if($img_thumb_id==0){
            $img_thumb_id=$img_url_id;
        }
        return array('img_small_id'=>$img_small_id,'img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id);
        
    }
   /**
     * 共用-在数据表sys_image写入新图片
     * @param unknown $image_addr
     * @param unknown $image_url
     * @param unknown $image_w
     * @param unknown $image_h
     * @return boolean
     */
    public function newimage($image_name,$image_addr,$file_menu,$image_w,$image_h)
    {
    	$model_image = new Image();
    	$model_image->name = $image_name;
    	$model_image->url = $image_addr;
    	$model_image->type = $file_menu;
    	$model_image->width = $image_w;
    	$model_image->height = $image_h;
		$model_image->update_time = time();
    	if($model_image->save())
    	{
    		return $model_image->id;
    		
    	}
    }
    /**
     * 修改图片
     */
    public function updateimage($id,$image_name, $image_w, $image_h,$img_url){
        $img_model=SysImage::findOne($id);
        $img_model->name=$image_name;
        $img_model->width=$image_w;
        $img_model->height=$image_h;
        $img_model->url=$img_url;
        $result=$img_model->save();
        return $result;
    }
    /*
     * 脚批量修改时，可以用
     * 
     * 
     /
    public function actionChangeSmallimageOld()
    {
    	
    	$model = Image::findBySql('SELECT * FROM sys_image WHERE url not like "%\_2%" and url not like "%\_1%" and id>19000 and id <= 21000')->all();
		
    	//var_dump($model);
    	foreach ($model as $value)
    	{
    	//	echo $value->url;
    		
	    	$file_name = explode('.', $value->url)[0]."_2";//小图的名字
	    	$file_extend = explode('.', $value->url)[1];//小图的扩展名
	    	$file_name_save = implode('.', array($file_name,$file_extend)); //存入文件的名称 url
	    	
	    	$model_small = Image::findOne(['url' => $file_name_save]);
	    	echo $file_name_save;
	    	if($model_small != null)
	    	{
	    			//有小图的情况下，传入小图
	    			
	    			$small = new GD(Yii::getAlias('@webroot').'/'.$value->url);//原图		
	    			$small->resizePercent(25);
	    			$small->save(Yii::getAlias('@webroot').'/'.$file_name_save); //存入文件夹
	    			 //获取图片的宽和高
	    			$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_name_save)[0]; //获取图片的宽
	    			$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_name_save)[1]; //获取图片的高
					//更改信息
	    			$model_small->width = $image_w_small;
	    			$model_small->height = $image_h_small;
	    			if($model_small->save())
	    			{
	    				echo 'ok';
	    				//echo '<img src='.$model_small->url.' />'.$model_small->width.'X'.$model_small->height;
	    			}
	    	}  
    	}
    	echo '完成本批';
    }
    */
    public function actionSelectImageTypeid()
    {
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	return $this->render('select_image_type',[
    			'model' => $model,
    			]);
    		
    }
    public function actionWriteTypeidToCookie($typeid)
    {
    	
    	$cookies = Yii::$app->response->cookies;
    	$cookies->add(new \yii\web\Cookie([
    			'name' => 'image_typeid',
    			'value' => $typeid,
    			]));
    	
    	$cookies = Yii::$app->request->cookies;
    	if(isset($cookies['image_typeid']))
    	{
    		$image_typeid = $cookies['image_typeid']->value;
    		//echo $image_typeid;
    		
    	}
    	return $image_typeid;
    }
	    /*选择套装存入cookies*/
    public function actionWriteTzToCookie()
    {
    	var_dump($_GET['arr_tz']);
    	/*
    	$arr_tz_new = array();
    	foreach ($_GET as $k => $v){
    		if($k == 'arr_tz'){
    			array_push($arr_tz_new, $v);
    		}
    	}
    	var_dump($arr_tz_new);
    	$cookies = Yii::$app->response->cookies;
    	$cookies->add(new \yii\web\Cookie([
    			'name' => 'arr_tz',
    			'value' => $arr_tz_new,
    			]));
    	 
    	$cookies = Yii::$app->request->cookies;
    	if(isset($cookies['arr_tz']))
    	{
    		//$tz_list = implode(',',$cookies['arr_tz']->value);
    		$tz_list = $cookies['arr_tz']->value;
    		var_dump($tz_list);
    		//echo $image_typeid;
    
    	}*/
    	return 1;
    }
    /*
    *图片管理新增请求子级树
    *skt 2019 2.22
    */
    public function actionChildTree()
    {
        $addr=Yii::$app->request->get("addr");
        $data=[
            'status'=>0,
            'data'=>[],
        ];
        if(!empty($addr)){
             $model_tree_addr = PrfType::findBySql("select * from prf_type where addr REGEXP '".$addr."/[a-zA-Z0-9\_]*$'")->asArray()->all();
             $data['status']=1;
                if ($model_tree_addr != null)
                {
                 foreach ($model_tree_addr as $value)
                 {
                     $model_tree_addr_child = PrfType::findBySql("select * from prf_type where addr REGEXP '".$value['addr']."/[a-zA-Z0-9\_]*$'")->all();
                        
                     if($model_tree_addr_child != null)
                     {
                        $value['child']='true';
                        $data['data'][]=$value;
                        
                     }
                        
                     else if($model_tree_addr_child == null)
                     {
                        $value['child']='false';
                        $data['data'][]=$value;
                     }
                 }
                return json_encode($data);
            }
        }else{
            return json_encode($data);
        }
    }
    /**
     * 删除图片 
     * lwx 10.17
     */
    
    public  function  actionDelImage($ids){
        $result=2;
        if($ids!=""){
            $ids=explode(",", $ids);
            //删除图片 再删除sys_image数据
            for($i=0;$i<count($ids);$i++){
                $image=SysImage::findOne($ids[$i]);
                if($image){
                    $url=$image->url;
                    $result=unlink($url);
                    if($result){
                        $result=$image->delete();
                    }else{
                        $result=2;
                    } 
                    if($result){
                        $result= 1; 
                    }else{
                        $result= 0; 
                    }
                    
                }else{
                    $result=2;
                }
               
            }
            echo $result;  exit();
        }else{
            echo $result;exit();
        }
        
    }
    
   
}
